package com.socialsoftware.Page;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.socialsoftware.R;
import com.socialsoftware.adapter.FriendRequestAdapter;
import com.socialsoftware.model.FriendRequest;
import com.socialsoftware.repository.FriendRequestRepository;
import com.socialsoftware.viewmodel.FriendRequestViewModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 好友请求页面
 * 显示所有收到的好友请求，可以接受、拒绝或拉黑
 */
public class FriendRequestsActivity extends AppCompatActivity implements FriendRequestAdapter.OnRequestActionListener {
    
    private static final String TAG = "FriendRequestsActivity";
    
    // UI组件
    private RecyclerView recyclerViewRequests;
    private LinearLayout emptyState;
    private ProgressBar progressBar;
    private SwipeRefreshLayout swipeRefreshLayout;
    
    // 数据
    private FriendRequestAdapter adapter;
    private final List<FriendRequest> friendRequests = new ArrayList<>();
    private FriendRequestViewModel viewModel;
    private FriendRequestRepository repository;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_requests);
        
        // 初始化UI组件
        initViews();
        
        // 设置工具栏
        setupToolbar();
        
        // 设置RecyclerView
        setupRecyclerView();
        
        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(FriendRequestViewModel.class);
        
        // 初始化Repository
        repository = new FriendRequestRepository(getApplication());
        
        // 加载数据
        loadData();
    }
    
    private void initViews() {
        recyclerViewRequests = findViewById(R.id.recycler_view_requests);
        emptyState = findViewById(R.id.empty_state);
        progressBar = findViewById(R.id.progress_bar);
        
        // 添加下拉刷新控件
        swipeRefreshLayout = new SwipeRefreshLayout(this);
        swipeRefreshLayout.setLayoutParams(new SwipeRefreshLayout.LayoutParams(
                SwipeRefreshLayout.LayoutParams.MATCH_PARENT,
                SwipeRefreshLayout.LayoutParams.MATCH_PARENT));
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, 
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        
        // 设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener(() -> {
            // 刷新数据
            refreshData();
        });
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
        
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }
    
    private void setupRecyclerView() {
        adapter = new FriendRequestAdapter(this, friendRequests, this);
        recyclerViewRequests.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewRequests.setAdapter(adapter);
    }
    
    private void loadData() {
        // 显示加载中状态
        showLoading();
        
        // 从ViewModel获取数据
        LiveData<List<FriendRequest>> requestsLiveData = viewModel.getFriendRequests();
        if (requestsLiveData != null) {
            requestsLiveData.observe(this, requests -> {
                if (requests != null && !requests.isEmpty()) {
                    friendRequests.clear();
                    friendRequests.addAll(requests);
                    adapter.notifyDataSetChanged();
                    showContent();
                } else {
                    showEmptyState();
                }
            });
        } else {
            // 如果LiveData为null，显示空状态
            showEmptyState();
        }
        
        // 从服务器刷新数据
        refreshData();
    }
    
    private void refreshData() {
        // 从服务器获取最新数据
        repository.fetchPendingRequestsFromServer();
        
        // 模拟网络延迟，1秒后结束刷新动画
        new android.os.Handler().postDelayed(() -> {
            if (swipeRefreshLayout != null) {
                swipeRefreshLayout.setRefreshing(false);
            }
        }, 1000);
    }
    
    private void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        recyclerViewRequests.setVisibility(View.GONE);
        emptyState.setVisibility(View.GONE);
    }
    
    private void showContent() {
        progressBar.setVisibility(View.GONE);
        recyclerViewRequests.setVisibility(View.VISIBLE);
        emptyState.setVisibility(View.GONE);
    }
    
    private void showEmptyState() {
        progressBar.setVisibility(View.GONE);
        recyclerViewRequests.setVisibility(View.GONE);
        emptyState.setVisibility(View.VISIBLE);
    }
    
    @Override
    public void onAcceptRequest(FriendRequest request) {
        // 显示确认对话框
        new AlertDialog.Builder(this)
                .setTitle("接受好友请求")
                .setMessage("确定要添加 " + request.getRequesterName() + " 为好友吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 调用接受好友请求的API
                    repository.acceptFriendRequest(request, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            runOnUiThread(() -> {
                                Toast.makeText(FriendRequestsActivity.this, 
                                        "接受好友请求失败，请稍后重试", Toast.LENGTH_SHORT).show();
                            });
                        }
                        
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            runOnUiThread(() -> {
                                if (response.isSuccessful()) {
                                    // 更新UI
                                    adapter.updateRequestStatus(request.getId(), FriendRequestAdapter.STATUS_ACCEPTED);
                                    Toast.makeText(FriendRequestsActivity.this, 
                                            "已添加 " + request.getRequesterName() + " 为好友", 
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(FriendRequestsActivity.this, 
                                            "接受好友请求失败: " + response.code(), 
                                            Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    });
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    @Override
    public void onRejectRequest(FriendRequest request) {
        // 显示确认对话框
        new AlertDialog.Builder(this)
                .setTitle("拒绝好友请求")
                .setMessage("确定要拒绝 " + request.getRequesterName() + " 的好友请求吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 调用拒绝好友请求的API
                    repository.rejectFriendRequest(request, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            runOnUiThread(() -> {
                                Toast.makeText(FriendRequestsActivity.this, 
                                        "拒绝好友请求失败，请稍后重试", Toast.LENGTH_SHORT).show();
                            });
                        }
                        
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            runOnUiThread(() -> {
                                if (response.isSuccessful()) {
                                    // 更新UI
                                    adapter.updateRequestStatus(request.getId(), FriendRequestAdapter.STATUS_REJECTED);
                                    Toast.makeText(FriendRequestsActivity.this, 
                                            "已拒绝 " + request.getRequesterName() + " 的好友请求", 
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(FriendRequestsActivity.this, 
                                            "拒绝好友请求失败: " + response.code(), 
                                            Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    });
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    @Override
    public void onMoreOptions(FriendRequest request, View anchorView) {
        // 显示更多选项菜单
        PopupMenu popupMenu = new PopupMenu(this, anchorView);
        popupMenu.getMenu().add(0, 1, 0, "拉黑该用户");
        popupMenu.getMenu().add(0, 2, 0, "举报");
        
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case 1:
                        // 拉黑用户
                        blockUser(request);
                        return true;
                    case 2:
                        // 举报用户
                        reportUser(request);
                        return true;
                    default:
                        return false;
                }
            }
        });
        
        popupMenu.show();
    }
    
    /**
     * 拉黑用户
     */
    private void blockUser(FriendRequest request) {
        // 显示确认对话框
        new AlertDialog.Builder(this)
                .setTitle("拉黑用户")
                .setMessage("确定要拉黑 " + request.getRequesterName() + " 吗？拉黑后对方将无法向你发送消息和好友请求。")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 调用拉黑用户的API
                    repository.blockUser(request.getRequesterId(), new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            runOnUiThread(() -> {
                                Toast.makeText(FriendRequestsActivity.this, 
                                        "拉黑用户失败，请稍后重试", Toast.LENGTH_SHORT).show();
                            });
                        }
                        
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            runOnUiThread(() -> {
                                // 无论API是否成功，都更新本地状态
                                adapter.updateRequestStatus(request.getId(), FriendRequestAdapter.STATUS_BLOCKED);
                                Toast.makeText(FriendRequestsActivity.this, 
                                        "已拉黑 " + request.getRequesterName(), 
                                        Toast.LENGTH_SHORT).show();
                            });
                        }
                    });
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    /**
     * 举报用户
     */
    private void reportUser(FriendRequest request) {
        // 显示举报选项对话框
        final String[] reportOptions = {
                "垃圾信息",
                "色情低俗",
                "欺诈信息",
                "政治敏感",
                "侵犯隐私",
                "其他原因"
        };
        
        new AlertDialog.Builder(this)
                .setTitle("举报用户")
                .setItems(reportOptions, (dialog, which) -> {
                    String reason = reportOptions[which];
                    Toast.makeText(FriendRequestsActivity.this, 
                            "已举报用户: " + reason, Toast.LENGTH_SHORT).show();
                    
                    // TODO: 调用举报API
                })
                .setNegativeButton("取消", null)
                .show();
    }
} 